package com.czmh.etc.onlinepubsys.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.czmh.etc.common.core.annotation.ApiVersion;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CurrentContext;
import com.czmh.etc.onlinepubsys.json.JsonResult;
import com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult;
import com.czmh.etc.onlinepubsys.model.EtcDevice;
import com.czmh.etc.onlinepubsys.model.EtcObuDTO;
import com.czmh.etc.onlinepubsys.services.EtcApplyInfoService;
import com.czmh.etc.onlinepubsys.services.EtcOrderService;
import com.czmh.etc.onlinepubsys.services.JyService;
import com.czmh.etc.onlinepubsys.services.mingchuang.ICurrentContextService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IEtcOrderService;
import com.czmh.etc.onlinepubsys.utils.DatetimeUtil;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName：JyController
 * @Description：上海久誉对接控制器
 * @Author： Chenzj.
 * @Date：2020/09/21 10:33.
 * @Version：1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/{version}/api/jy/")
@Api(tags = "上海久誉接口")
public class JyController {
    @Autowired
    private EtcOrderService orderService;

    @Autowired
    private JyService jyService;

    @Autowired
    private RedisUtil redisUtil;


    @Autowired
    private ICurrentContextService currentContextService;

    /**
     * 车辆预申请
     *
     * @param orderNo 不可为空! 订单号
     * @return
     */
    @ApiVersion(1)
    @RequestMapping(value = "/carPreApplication", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "车辆预申请", notes = "车辆预申请")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "userId", value = "用户id", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "orderNo", value = "订单号", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "vehicleNumber", value = "车牌号码", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "vehicleColor", value = "车牌颜色", required = true)

    })
    public JsonResult carPreApplication(@RequestParam String userId, @RequestParam String orderNo, @RequestParam String vehicleNumber, @RequestParam String vehicleColor) {
        if (null == orderNo || null == vehicleNumber || null == vehicleColor || null == userId) {
            JsonResult result = new JsonResult();
            result.setCode(JSONResult.FAIL);
            result.setMessage("请求参数异常，请检查！");
            return result;
        }
        return jyService.carPreApplication(userId, orderNo, vehicleNumber, vehicleColor);
    }

    /**
     * 取消车辆预申请
     *
     * @param orderNo 不可为空! 订单号
     * @return
     */
    @ApiVersion(1)
    @RequestMapping(value = "/cancelCarPreApplication", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "取消车辆预申请", notes = "取消车辆预申请")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "orderNo", value = "订单号", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "reason", value = "取消车辆预申请原因", required = true)

    })
    public JsonResult cancelCarPreApplication(@RequestParam String orderNo, @RequestParam String reason) {
        if (null == orderNo || null == reason) {
            JsonResult result = new JsonResult();
            result.setCode(JSONResult.FAIL);
            result.setMessage("请求参数异常，请检查！");
            return result;
        }
        return jyService.cancelCarPreApplication(orderNo, reason);
    }

    /**
     * 申请单进度查询
     *
     * @param orderNo 不可为空! 订单号
     * @return
     */
    @ApiVersion(1)
    @RequestMapping(value = "/queryApplicationStatus", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "申请单进度查询", notes = "申请单进度查询")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "orderNo", value = "订单号", required = true)

    })
    public JsonResult queryApplicationStatus(@RequestParam String orderNo) {
        if (null == orderNo) {
            JsonResult result = new JsonResult();
            result.setCode(JSONResult.FAIL);
            result.setMessage("请求参数异常，请检查！");
            return result;
        }
        return jyService.queryApplicationStatus(orderNo);
    }

    /**
     * 根据产品编码获取产品状态
     *
     * @param productSn 产品编码
     * @return
     */
    @ApiVersion(1)
    //@PostMapping("/queryByProductSn")
    @RequestMapping(value = "/queryByProductSn", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "根据产品编码获取产品状态：0产品不存在,1产品未使用,2产品已使用", notes = "根据产品编码获取产品状态")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "productSn", value = "产品编码", required = true)
    })
    public JsonResult queryByProductSn(@RequestParam String productSn) {
        JsonResult result = new JsonResult();
        //发行方系统维护提示
        Object isRepair = redisUtil.get("isRepair");
        if(isRepair != null && isRepair.toString().equalsIgnoreCase("1")){
            Object repairTimeList = redisUtil.get("repairTimeList");
            if(repairTimeList != null){
                JSONArray jsonArray = JSON.parseArray(repairTimeList.toString());
                try {
                    Date current = new Date();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject object = (JSONObject) jsonArray.get(i);
                        Date beginTime = DatetimeUtil.parseSQLDate(object.getString("beginTime"), DatetimeUtil.STANDARD_DATETIME_PATTERN);
                        Date endTime = DatetimeUtil.parseSQLDate(object.getString("endTime"), DatetimeUtil.STANDARD_DATETIME_PATTERN);
                        if(beginTime.getTime() < current.getTime() && endTime.getTime() > current.getTime()){
                            result.setCode(JSONResult.FAIL);
                            result.setMessage("系统" + object.getString("beginTime") + "-" + object.getString("endTime") + "升级期间将无法正常发行ETC，请稍后再试！");
                            return result;
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        if(StringUtils.isEmpty(productSn)){
            result.setCode(JSONResult.FAIL);
            result.setMessage("参数异常");
            return result;
        }
        JSONObject jsonObject = new JSONObject();
        int state = orderService.isExistProductSn(productSn);
        //判断产品编码对应的产品是否存在
        if (state == 0) {
            result.setCode(JSONResult.SUCCESS);
            result.setMessage("产品不存在");
            jsonObject.put("state", 0);
            jsonObject.put("etcDevice", null);
            result.setData(jsonObject);
            return result;
        } else {
            //产品存在需要判断产品是否被支付
            Integer count = orderService.queryEtcPayState(productSn, 1);
            if (count == null || count.intValue() == 0) {
                Map<String, Object> queryMap = new HashMap<>();
                queryMap.put("deleteFlag", "0");
                queryMap.put("productSn", productSn);
                EtcDevice etcDevice = orderService.queryObject(queryMap);
                //产品发行方如果是西藏或者招商局统一走招商发行渠道
                if(etcDevice.getIssuerName().equalsIgnoreCase("西藏") || etcDevice.getIssuerName().equalsIgnoreCase("招商")){
                    etcDevice.setIssuerName("招商");
                }
                result.setCode(JSONResult.SUCCESS);
                result.setMessage("产品可用");
                jsonObject.put("state", 1);
                jsonObject.put("etcDevice", etcDevice);
                //发行方渠道配置选择
                String issueName = redisUtil.getIssueName();
                if(issueName != null){
                    etcDevice.setIssuerName(issueName);
                    jsonObject.put("etcDevice", etcDevice);
                }
                result.setData(jsonObject);
                return result;
            } else {
                result.setCode(JSONResult.SUCCESS);
                result.setMessage("产品不可用");
                jsonObject.put("state", 2);
                jsonObject.put("etcDevice", null);
                result.setData(jsonObject);
                return result;
            }
        }
    }


}
